package top.fullj.actor.mq;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FiberPool {

    public static final String PROP_FIBER_COUNT = "top.fullj.jactor.fiber.count";

    private static final int NUMBER_OF_FIBERS;

    static {
        String fiberCount = System.getProperty(PROP_FIBER_COUNT, "2");
        NUMBER_OF_FIBERS = Integer.parseInt(fiberCount);
    }

    private static final FiberPool INSTANCE = new FiberPool(NUMBER_OF_FIBERS);

    public static Fiber assign(String key) {
        return INSTANCE.select(key);
    }

    private final List<ThreadExecutorFiber> fibers;

    private FiberPool(int count) {
        if (count <= 0) {
            throw new IllegalArgumentException("count=" + count);
        }
        this.fibers = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            this.fibers.add(new ThreadExecutorFiber());
        }
    }

    private ThreadExecutorFiber select(@SuppressWarnings("unused") String key) {
        synchronized (this.fibers) {
            // min activity
            return Collections.min(this.fibers);
        }
        // consistency hash
        /*int index = Math.abs(key.hashCode() % fibers.size());
        return fibers.get(index);*/
    }

}
